package com.liuyk.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.liuyk.broadcast.CloseAppBroadcastReceiver;
import com.liuyk.util.AppUtils;
import com.tbruyelle.rxpermissions3.RxPermissions;

/**
 * 基类activity
 * <p>
 * Created by Administrator on 2015/9/9.
 */
public abstract class BaseActivity extends AppCompatActivity {
    protected static final String TAG = "BaseMain";

    protected static final int PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1001;
    protected static final int PERMISSIONS_READ_EXTERNAL_STORAGE = 1002;
    protected static final int PERMISSIONS_READ_PHONE_STATE = 1003;
    protected static final int PERMISSIONS_CAMERA = 1004;
    protected static final int PERMISSIONS_AUDIO = 1005;


    // do not repeat yourself
    private CloseAppBroadcastReceiver mCloseAppReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCloseAppReceiver = new CloseAppBroadcastReceiver(this);
        Log.i("process", AppUtils.getProcessName(this));
    }

    /**
     * 退出应用
     *
     * @param context 应用上下文
     */
    public void closeApp(Context context) {
        mCloseAppReceiver.closeApp(context);
    }


    protected void checkPermissions() {
        checkWriteExternalStorage();
    }

    protected void checkWriteExternalStorage() {
        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        //为了帮助查找用户可能需要解释的情形，Android 提供了一个实用程序方法，
        //即 shouldShowRequestPermissionRationale()。如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true
        //注：如果用户在过去拒绝了权限请求，并在权限请求系统对话框中选择了 Don’t ask again 选项，此方法将返回 false
        // 如果设备规范禁止应用具有该权限，此方法也会返回 false
        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])) {
            //用户拒绝，并且勾了不再提示，这时候只能跳转到设置页
        }

        //如果应用具有此权限，方法将返回 PackageManager.PERMISSION_GRANTED，并且应用可以继续操作。
        //如果应用不具有此权限，方法将返回 PERMISSION_DENIED，且应用必须明确向用户要求权限。
        int permissionCheck = ContextCompat.checkSelfPermission(this, permissions[0]);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            //有权限
            checkPhoneState();
        } else {
            //没有权限
            ActivityCompat.requestPermissions(this, permissions, PERMISSIONS_WRITE_EXTERNAL_STORAGE);
        }
    }


    private void checkPhoneState() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.CAMERA)
                .subscribe(granted -> {
                    if (granted) { // Always true pre-M
                        // I can control the camera now
                        checkRecordAudio();
                    } else {
                        checkRecordAudio();
                    }
                });
    }

    private void checkRecordAudio() {
        String[] permissions = {Manifest.permission.RECORD_AUDIO};
        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])) {
            //用户拒绝，并且勾了不再提示，这时候只能跳转到设置页
        }
        int permissionCheck = ContextCompat.checkSelfPermission(this, permissions[0]);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            permissionsGranted(PERMISSIONS_AUDIO);
        } else {
            ActivityCompat.requestPermissions(this, permissions, PERMISSIONS_AUDIO);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_WRITE_EXTERNAL_STORAGE:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    permissionsGranted(PERMISSIONS_WRITE_EXTERNAL_STORAGE);
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    permissionsDenied(PERMISSIONS_WRITE_EXTERNAL_STORAGE);
                }
                checkPhoneState();
                break;

            case PERMISSIONS_CAMERA:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    permissionsGranted(PERMISSIONS_CAMERA);
                } else {
                    permissionsDenied(PERMISSIONS_CAMERA);
                }
                checkRecordAudio();
                break;

            case PERMISSIONS_AUDIO:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    permissionsGranted(PERMISSIONS_AUDIO);
                } else {
                    permissionsDenied(PERMISSIONS_AUDIO);
                }
                break;
        }
    }

    //权限允许
    protected void permissionsGranted(int code) {

    }

    //权限拒绝
    protected void permissionsDenied(int code) {

    }

    protected void showToast(String s) {
        Toast.makeText(this, s, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCloseAppReceiver.unRegisterSelf(this);
    }

}
